//
//  RegistVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/6/29.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "RegistVC.h"
#import "RegistDelegateVC.h"
#import "CommitSuccessVC.h"
#import "XLPhotoBrowser.h"

@interface RegistVC ()<TZImagePickerControllerDelegate,XLPhotoBrowserDelegate> {
    BOOL isAgree;
    NSData *selectImgData;
}

@property (nonatomic, strong) UITextField *companyField;
@property (nonatomic, strong) UIImageView *iconImgView;
@property (nonatomic, strong) UIButton *iconBtn;
@property (nonatomic, strong) UITextField *phoneField;
@property (nonatomic, strong) UITextField *codeField;
@property (nonatomic, strong) UIButton *getCodeBtn;
@property (nonatomic, strong) UITextField *pwdField;
@property (nonatomic, strong) UIButton *showBtn;
@property (nonatomic, strong) UIButton *agreeBtn;
@property (nonatomic, strong) UIButton *delegateBtn;
@property (nonatomic, strong) UIButton *commitBtn;
@property (nonatomic, strong) UIButton *logBtn;

@end

@implementation RegistVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"企业注册";
    isAgree = YES;
    [self configUI];
}

- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *companyTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, 30, ScreenW - 80, 13)];
    companyTitleLab.text = @"公司名称";
    companyTitleLab.font = [UIFont systemFontOfSize:12];
    companyTitleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:companyTitleLab];
    
    self.companyField = [[UITextField alloc] initWithFrame:CGRectMake(40, companyTitleLab.nim_bottom + 2, companyTitleLab.nim_width, 40)];
    self.companyField.placeholder = @"请输入营业执照上登记的企业全称";
    self.companyField.font = MediumFontOfSize(16);
    self.companyField.textColor = HexColor(0x2B2C44);
    [self.view addSubview:self.companyField];
    
    UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake(40, self.companyField.nim_bottom, self.companyField.nim_width, 1)];
    line1.backgroundColor = HexColor(0xF2F2F5);
    [self.view addSubview:line1];
    
    UILabel *iconTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, line1.nim_bottom + 20, line1.nim_width, 13)];
    iconTitleLab.text = @"营业执照";
    iconTitleLab.font = [UIFont systemFontOfSize:12];
    iconTitleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:iconTitleLab];
    
    self.iconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, iconTitleLab.nim_bottom + 6, 30, 30)];
    [self.view addSubview:self.iconImgView];
    
    UIButton *imgBtn = [[UIButton alloc] initWithFrame:self.iconImgView.frame];
    [imgBtn addTarget:self action:@selector(imgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imgBtn];
    
    self.iconBtn = [[UIButton alloc] initWithFrame:CGRectMake(iconTitleLab.nim_right - 108, iconTitleLab.nim_bottom + 6, 108, 30)];
    self.iconBtn.layer.cornerRadius = 15;
    [self.iconBtn setBackgroundColor:HexColorA(0x3D68EB, 0.1)];
    [self.iconBtn setTitleColor:HexColor(0x3D68EB) forState:0];
    [self.iconBtn setTitle:@"上传图片" forState:0];
    self.iconBtn.titleLabel.font = BoldFontOfSize(14);
    [self.iconBtn setImage:[UIImage imageNamed:@"icon_regist_upload"] forState:0];
    [self.iconBtn addTarget:self action:@selector(chooseImg) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.iconBtn];
    
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(40, self.iconBtn.nim_bottom + 6, self.companyField.nim_width, 1)];
    line2.backgroundColor = HexColor(0xF2F2F5);
    [self.view addSubview:line2];
    
    UILabel *phoneTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, line2.nim_bottom + 20, iconTitleLab.nim_width, 13)];
    phoneTitleLab.text = @"手机号";
    phoneTitleLab.font = [UIFont systemFontOfSize:12];
    phoneTitleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:phoneTitleLab];
    
    self.phoneField = [[UITextField alloc] initWithFrame:CGRectMake(40, phoneTitleLab.nim_bottom + 2, phoneTitleLab.nim_width, 40)];
    self.phoneField.placeholder = @"请输入手机号";
    self.phoneField.font = MediumFontOfSize(16);
    self.phoneField.textColor = HexColor(0x2B2C44);
    [self.view addSubview:self.phoneField];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, self.phoneField.nim_height)];
    UILabel *phoneLeftLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, self.phoneField.nim_height-2)];
    phoneLeftLab.text = @"+86";
    phoneLeftLab.textColor = HexColor(0x2B2C44);
    phoneLeftLab.font = MediumFontOfSize(16);
    [leftView addSubview:phoneLeftLab];
    self.phoneField.leftView = leftView;
    self.phoneField.leftViewMode = UITextFieldViewModeAlways;
    
    UILabel *line3 = [[UILabel alloc] initWithFrame:CGRectMake(40, self.phoneField.nim_bottom, self.phoneField.nim_width, 1)];
    line3.backgroundColor = HexColor(0xF2F2F5);
    [self.view addSubview:line3];
    
    UILabel *codeTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, line3.nim_bottom + 20, iconTitleLab.nim_width, 13)];
    codeTitleLab.text = @"短信验证码";
    codeTitleLab.font = [UIFont systemFontOfSize:12];
    codeTitleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:codeTitleLab];
    
    self.codeField = [[UITextField alloc] initWithFrame:CGRectMake(40, codeTitleLab.nim_bottom + 2, codeTitleLab.nim_width, 40)];
    self.codeField.placeholder = @"请输入验证码";
    self.codeField.font = MediumFontOfSize(16);
    self.codeField.textColor = HexColor(0x2B2C44);
    [self.view addSubview:self.codeField];
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 102, 40)];
    self.getCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 102, 30)];
    self.getCodeBtn.layer.cornerRadius = 15;
    [self.getCodeBtn setBackgroundColor:HexColorA(0x3D68EB, 0.1)];
    [self.getCodeBtn setTitleColor:HexColor(0x3D68EB) forState:0];
    [self.getCodeBtn setTitle:@"获取验证码" forState:0];
    self.getCodeBtn.titleLabel.font = BoldFontOfSize(14);
    [self.getCodeBtn addTarget:self action:@selector(getCodeClick) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:self.getCodeBtn];
    self.codeField.rightView = rightView;
    self.codeField.rightViewMode = UITextFieldViewModeAlways;
    
    UILabel *line4 = [[UILabel alloc] initWithFrame:CGRectMake(40, self.codeField.nim_bottom, self.codeField.nim_width, 1)];
    line4.backgroundColor = HexColor(0xF2F2F5);
    [self.view addSubview:line4];
    
    UILabel *pwdTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, line4.nim_bottom + 20, iconTitleLab.nim_width, 13)];
    pwdTitleLab.text = @"密码";
    pwdTitleLab.font = [UIFont systemFontOfSize:12];
    pwdTitleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:pwdTitleLab];
    
    self.pwdField = [[UITextField alloc] initWithFrame:CGRectMake(40, pwdTitleLab.nim_bottom + 2, pwdTitleLab.nim_width, 40)];
    self.pwdField.placeholder = @"请输入密码";
    self.pwdField.font = MediumFontOfSize(16);
    self.pwdField.textColor = HexColor(0x2B2C44);
    self.pwdField.secureTextEntry = YES;
    [self.view addSubview:self.pwdField];
    
    self.showBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    [self.showBtn setImage:[UIImage imageNamed:@"pwd_hide"] forState:0];
    [self.showBtn addTarget:self action:@selector(showBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.pwdField.rightView = self.showBtn;
    self.pwdField.rightViewMode = UITextFieldViewModeAlways;
    
    UILabel *line5 = [[UILabel alloc] initWithFrame:CGRectMake(40, self.pwdField.nim_bottom, self.pwdField.nim_width, 1)];
    line5.backgroundColor = HexColor(0xF2F2F5);
    [self.view addSubview:line5];
    
    self.agreeBtn = [[UIButton alloc] initWithFrame:CGRectMake(40, line5.nim_bottom + 10, 18, 18)];
    [self.agreeBtn setImage:[UIImage imageNamed:isAgree?@"icon_agreement_sel":@"icon_agreement"] forState:0];
    [self.agreeBtn addTarget:self action:@selector(agreeClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.agreeBtn];
    
    UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(self.agreeBtn.nim_right, self.agreeBtn.nim_top, [FactoryMethod sizeWithText:@"我已阅读并同意" font:BoldFontOfSize(12) maxSize:CGSizeMake(0, 0)].width, [FactoryMethod sizeWithText:@"我已阅读并同意" font:BoldFontOfSize(12) maxSize:CGSizeMake(0, 0)].height)];
    lab1.text = @"我已阅读并同意";
    lab1.font = BoldFontOfSize(12);
    lab1.textColor = HexColor(0x9C9DB3);
    [self.view addSubview:lab1];
    lab1.nim_centerY = self.agreeBtn.nim_centerY;
    
    self.delegateBtn = [[UIButton alloc] initWithFrame:CGRectMake(lab1.nim_right, lab1.nim_top, [FactoryMethod sizeWithText:@"用户注册及服务协议" font:BoldFontOfSize(12) maxSize:CGSizeMake(0, 0)].width, [FactoryMethod sizeWithText:@"用户注册及服务协议" font:BoldFontOfSize(12) maxSize:CGSizeMake(0, 0)].height)];
    [self.delegateBtn setTitle:@"用户注册及服务协议" forState:0];
    self.delegateBtn.titleLabel.font = BoldFontOfSize(12);
    [self.delegateBtn setTitleColor:HexColor(0x3D68EB) forState:0];
    [self.delegateBtn addTarget:self action:@selector(delegateClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.delegateBtn];
    self.delegateBtn.nim_centerY = self.agreeBtn.nim_centerY;
    
    self.commitBtn = [[UIButton alloc] initWithFrame:CGRectMake(40, self.agreeBtn.nim_bottom + 30, ScreenW - 80, 44)];
    [self.commitBtn setTitle:@"提交注册申请" forState:0];
    [self.commitBtn setTitleColor:HexColor(0xffffff) forState:0];
    self.commitBtn.titleLabel.font = BoldFontOfSize(16);
    [self.commitBtn setBackgroundColor:HexColor(0x3D68EB)];
    self.commitBtn.layer.masksToBounds = YES;
    self.commitBtn.layer.cornerRadius = 6;
    [self.commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.commitBtn];
    
    self.logBtn = [[UIButton alloc] initWithFrame:CGRectMake((ScreenW - [FactoryMethod sizeWithText:@"已有账号，直接登录" font:BoldFontOfSize(14) maxSize:CGSizeMake(0, 0)].width) * 0.5, self.commitBtn.nim_bottom + 20, [FactoryMethod sizeWithText:@"已有账号，直接登录" font:BoldFontOfSize(14) maxSize:CGSizeMake(0, 0)].width, [FactoryMethod sizeWithText:@"已有账号，直接登录" font:BoldFontOfSize(14) maxSize:CGSizeMake(0, 0)].height)];
    [self.logBtn setTitle:@"已有账号，直接登录" forState:0];
    [self.logBtn setTitleColor:HexColor(0x3D68EB) forState:0];
    self.logBtn.titleLabel.font = BoldFontOfSize(14);
    [self.logBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.logBtn];
}

- (void)imgBtnClick {
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:@[self.iconImgView.image] currentImageIndex:1];
    browser.browserStyle = XLPhotoBrowserStyleIndexLabel;//微博样式
    [browser setActionSheetWithTitle:nil delegate:self cancelButtonTitle:nil deleteButtonTitle:nil otherButtonTitles:@"保存图片", nil];
}

- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex {
    [browser saveCurrentShowImage];
}

- (void)loginClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

- (void)showBtnClick {
    self.pwdField.secureTextEntry = !self.pwdField.isSecureTextEntry;
    [self.showBtn setImage:[UIImage imageNamed:self.pwdField.isSecureTextEntry ? @"pwd_hide" : @"pwd_show"] forState:0];
}

- (void)delegateClick {
    RegistDelegateVC *vc = [RegistDelegateVC new];
    [self.rt_navigationController pushViewController:vc animated:YES];
}

- (void)commitClick {
    if (isAgree) {
        [self requestForRegist];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请同意用户注册及服务协议"];
    }
}

- (void)requestForRegist {
    if ([FactoryMethod isNull:self.companyField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入企业名称"];
        return;
    }
//    if (!self.iconImgView.image) {
//        [MBProgressHUD leShowFailedHUD:self.view message:@"请上传营业执照"];
//        return;
//    }
    if ([FactoryMethod isNull:self.phoneField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入手机号"];
        return;
    }
    if (![FactoryMethod isPhone:self.phoneField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入正确的手机号"];
        return;
    }
    if ([FactoryMethod isNull:self.codeField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入验证码"];
        return;
    }
    if ([FactoryMethod isNull:self.pwdField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入密码"];
        return;
    }
    [MBProgressHUD leShowHUDWithMessage:@"提交中" activity:YES];
//    [HttpRequest postImgWithUrl:LogisticsSupplierRegist imglist:self.iconImgView.image ? @[self.iconImgView.image] : @[] imgFile:@"license" withParameter:@{@"company_name":self.companyField.text,@"phone":self.phoneField.text,@"code":self.codeField.text,@"password":self.pwdField.text} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
//        if (code) {
//            __weak_self;
//            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"注册成功" delayOperation:^{
//                CommitSuccessVC *vc = [CommitSuccessVC new];
//                vc.companyNO = [responseObject objectForKey:@"company_no"];
//                vc.responseObject = responseObject;
//                [weakself.rt_navigationController pushViewController:vc animated:YES];
//            }];
//        }
//    } failure:^(NSError * _Nonnull error) {
//
//    }];
    [HttpRequest postImgDataWithUrl:LogisticsSupplierRegist imgData:self.iconImgView.image ? selectImgData : nil imgFile:@"license" withParameter:@{@"company_name":self.companyField.text,@"phone":self.phoneField.text,@"code":self.codeField.text,@"password":self.pwdField.text} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"注册成功" delayOperation:^{
                CommitSuccessVC *vc = [CommitSuccessVC new];
//                vc.companyNO = [responseObject objectForKey:@"company_no"];
//                vc.responseObject = responseObject;
                [weakself.rt_navigationController pushViewController:vc animated:YES];
            }];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)chooseImg {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//                NSData *logoImg = UIImageJPEGRepresentation(photos.firstObject, 0.5);
//                NSString *imgStr = [logoImg base64EncodedStringWithOptions:0];
//                NSString *dicStr = [NSString stringWithFormat:@"file=%@",imgStr];
//        [self requestForUpload:photos.firstObject];
        if (photos.count) {
            //通过asset获取原图，方法会先返回缩略图，再返回原图
            [[TZImageManager manager] getOriginalPhotoWithAsset:assets.firstObject newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                if ([info[PHImageResultIsDegradedKey] boolValue]) {
                    //返回的是缩略图
                }else {
                    //返回的是原图
                    [self.iconImgView setImage:photo];
                }
            }];
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:assets.firstObject progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
                
            } completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                self->selectImgData = data;
            }];
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)agreeClick {
    isAgree = !isAgree;
    [self.agreeBtn setImage:[UIImage imageNamed:isAgree?@"icon_agreement_sel":@"icon_agreement"] forState:0];
}

- (void)getCodeClick {
    if ([FactoryMethod isNull:self.phoneField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入手机号"];
        return;
    }
    if (![FactoryMethod isPhone:self.phoneField.text]) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请输入正确的手机号"];
        return;
    }
    [self timeStart];
    [self requestForGetCode];
}

- (void)requestForGetCode {
    [MBProgressHUD leShowHUDWithMessage:@"请求中" activity:YES];
    [HttpRequest PostWithApi:LogisticsSupplierGetRegistCode params:@{@"phone":self.phoneField.text,@"type":@(2)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"验证码获取成功"];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)timeStart{
    [self.codeField becomeFirstResponder];
    self.getCodeBtn.userInteractionEnabled = NO;
    self.codeField.text = @"";
    __block int timeout = 60; //倒计时时间
    /**
     *  gcd异步处理倒计时控件
     */
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.getCodeBtn.userInteractionEnabled = YES;
                [self.getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                [self.getCodeBtn setTitleColor:HexColor(0x3D68EB) forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.getCodeBtn.userInteractionEnabled = NO;
                NSString *strTime = [NSString stringWithFormat:@"%d S",seconds];
                [self.getCodeBtn setTitle:strTime forState:(UIControlStateNormal)];
                [self.getCodeBtn setTitleColor:HexColor(0x2B2C44) forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end
